<?php

class Request extends Kohana_Request {

	/**
	 * Main request singleton instance. If no URI is provided, the URI will
	 * be automatically detected using PATH_INFO, REQUEST_URI, or PHP_SELF.
	 *
	 * @param   string   URI of the request
	 * @return  Request
	 */
	public static function factory($uri = TRUE, HTTP_Cache $cache = NULL, $injected_routes = array())
	{
		$instance = parent::factory($uri, $cache);

		if(Arr::get(Kohana::modules(), "i18nUrl")) {
			if(!$instance->_external){

				$index_page = "";
				$lang_uri_abbr = Kohana::$config->load('lang.lang_uri_abbr');
				$default_lang = Kohana::$config->load('lang.language_abbr');
				$lang_ignore = Kohana::$config->load('lang.lang_ignore');

				/* get the lang_abbr from uri segments */
				$segments = explode('/',$instance->_uri);
				$lang_abbr = isset($segments[0]) ? $segments[0]:'';

				/* get current language */
				$cur_lang = $instance->param('lang',$default_lang);

				/* check for invalid abbreviation */
				if( ! isset($lang_uri_abbr[$lang_abbr]))
				{
					/* check for abbreviation to be ignored */
					if ($cur_lang != $lang_ignore) {

						/* check and set the default uri identifier */
						$index_page .= empty($index_page) ? $cur_lang : "/$cur_lang";

						/* redirect after inserting language id */
						header('Location: '.Url::base().$index_page . '/' . $instance->_uri);
						die();
					}


				}
			}
		}


		return $instance;
	}

	public function redirect($url = '', $code = 302) {
		if (strpos($url, '://') === FALSE) {
			// Make the URI into a URL
			$url = URL::site($url, TRUE, FALSE);
		}

		// Redirect
		$response = $this->create_response();

		if ($this->is_ajax() OR $this !== Request::current()) {
			$response->send_headers();

			echo json_encode(array('redirect' => TRUE, 'url' => $url));
		} else {
			// Set the response status
			$response->status($code);

			// Set the location header
			$response->headers('Location', $url);

			// Send headers
			$response->send_headers();
		}

		// Stop execution
		exit;
	}

}